﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Compilation;
using System.CodeDom;
using System.ComponentModel;
using System.Web.SessionState;

namespace MLY
{
    [ExpressionPrefix("Dict")]
    public class Dictionary : ExpressionBuilder
    {
        public const string ClientWorkOrderNumber = "ClienteditWoForm.clientWoNum"; // Client Work Order Number
        public const string SupplierWorkOrderNumber = "ContractoreditWoForm.contractorWoNum"; // Supplier Work Order Number
        public const string Quantity = "ContractoreditWoForm.Quantity";
        public const string SupplierId = "ContractoreditWoForm.ContractorId"; // Supplier Id

        private static Dict.lqDictDataContext _db;

        private static Dict.lqDictDataContext mDB
        {
            get
            {
                if (_db == null)
                    _db = CreateDB();
                return _db;
            }
        }

        private static Dict.lqDictDataContext CreateDB()
        {
            return new Dict.lqDictDataContext(g.AppConnectionString);
        }


        public static object GetEvalData(string expression, Type target, string entry)
        {
            return Translate(expression);
        }

        public static void UpdateTerm(string expression, string udpateStr)
        {
            try
            {
                //string userCulture = "";
                //System.Web.SessionState.HttpSessionState session = HttpContext.Current.Session;
                //userCulture = (session["Culture"] != null ? (string)session["Culture"] : "en");
                string culture = SessParam.Culture;

                if (Utils.SameText(culture, "en") || Utils.SameText(culture, "he"))
                {
                    Dal.lqKbmDataContext db = new Dal.lqKbmDataContext(g.AppConnectionString);
                    Dal.Dict _DataRow = (from t in db.Dicts
                                         where t.DictTerm == expression
                                         select t).FirstOrDefault();

                    if (Utils.SameText(culture, "en"))
                        _DataRow.en = udpateStr;
                    else
                        if (Utils.SameText(culture, "he"))
                            _DataRow.he = udpateStr;
                    db.SubmitChanges();
                }
            }
            catch
            {
            }
        }


        public static string Translate(string expression)
        {
            string result = expression;
            try
            {
                string culture = SessParam.Culture;
                string dictTerm = null;
                if (Utils.SameText(culture, "en") || Utils.SameText(culture, "he") || Utils.SameText(culture, "ru"))
                {
                    string sql = "select [" + culture + "] from Dict where [DictTerm]='" +
                                 expression.Replace("'", "''") + "'";
                    dictTerm = mDB.ExecuteQuery<string>(sql).FirstOrDefault();
                }
                if (dictTerm != null)
                    result = dictTerm;
                else
                {
                    if (mDB.Dicts.Count(x => x.DictTerm == expression) == 0)
                    {
                        Dict.lqDictDataContext _db2 = CreateDB();
                        Dict.Dict dict = new Dict.Dict();
                        dict.DictTerm = expression;
                        dict.InsertDate = DateTime.Now;
                        _db2.Dicts.InsertOnSubmit(dict);
                        _db2.SubmitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                result = expression;

                if (!ex.Message.StartsWith("Invalid column name "))
                    Log.WriteError(ex.Message);
            }
            return result;
        }

        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
                                                         object parsedData,
                                                         ExpressionBuilderContext context)
        {
            Type type1 = entry.DeclaringType;
            PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(type1)[entry.PropertyInfo.Name];
            CodeExpression[] expressionArray1 = new CodeExpression[3];
            expressionArray1[0] = new CodePrimitiveExpression(entry.Expression.Trim());
            expressionArray1[1] = new CodeTypeOfExpression(type1);
            expressionArray1[2] = new CodePrimitiveExpression(entry.Name);
            CodeExpression expression = new CodeMethodInvokeExpression(
                                        new CodeTypeReferenceExpression(base.GetType()), "GetEvalData", expressionArray1);
            CodeCastExpression result = new CodeCastExpression(descriptor1.PropertyType, expression);
            return result;
        }

        public override bool SupportsEvaluate
        {
            get { return true; }
        }

    }
}
